namespace OFX.Aggregator.Infrastructure
{
	#region #using Directives

	using System;

	#endregion

	public static class StatementFilter
	{
		public static void Filter(Statement statement, DateTime? dateStart, DateTime? dateEnd)
		{
			if (dateStart.HasValue)
			{
				if (dateStart > statement.DateStart)
				{
					statement.DateStart = dateStart.Value;
				}

				if (!dateEnd.HasValue && (statement.Flags & StatementFlags.AccurateDate) == StatementFlags.AccurateDate)
				{
					statement.DateEnd = statement.Date;
				}
			}
			if (dateEnd.HasValue && dateEnd < statement.DateEnd)
			{
				statement.DateEnd = dateEnd.Value;
			}

			foreach (var po in statement.PaymentOriginators)
			{
				po.StatementLines.RemoveAll(new DateRangePredicate(dateStart, dateEnd).Evaluator);
			}
		}

		#region Nested type: DateRangePredicate

		internal sealed class DateRangePredicate
		{
			private readonly DateTime? end;
			private readonly DateTime? start;

			public DateRangePredicate(DateTime? start, DateTime? end)
			{
				this.start = start;
				this.end = end;
			}

			public bool Evaluator(StatementLine transaction)
			{
				if (this.start.HasValue && transaction.DatePosted < this.start.Value)
				{
					return true;
				}
				if (this.end.HasValue && transaction.DatePosted > this.end.Value)
				{
					return true;
				}

				return false;
			}
		}

		#endregion
	}
}